package cn.h8k.hj212.example;

import cn.h8k.hj212.codec.Hj212EntityCodec;
import cn.h8k.hj212.config.Hj212Config;
import cn.h8k.hj212.entity.Hj212Message;
import cn.h8k.hj212.factory.Hj212EntityCodecFactory;
import cn.h8k.hj212.plugin.MonitoringFactorPlugin;
import cn.h8k.hj212.plugin.PluginManager;
import cn.h8k.hj212.plugin.impl.AtmosphericFactorPlugin;
import cn.h8k.hj212.version.ProtocolVersion;

/**
 * 增强功能演示
 * 展示新的插件化、版本适配、配置管理等功能
 * 
 * @author HJ212 Team
 * @since 1.0
 */
public class EnhancedFeatureDemo {
    
    private static final String SAMPLE_DATA = "##0131QN=20240709120000123;ST=31;CN=2011;PW=123456;MN=V130427GDSJ001;Flag=4;CP=&&DataTime=20240709120000;avoc01-Rtd=0.021,avoc01-Flag=N&&7BD3\r\n";
    
    public static void main(String[] args) {
        System.out.println("=== HJ212 增强功能演示 ===\n");
        
        // 1. 演示插件系统
        demonstratePluginSystem();
        
        // 2. 演示增强编解码器
        demonstrateEnhancedCodec();
        
        // 3. 演示配置管理
        demonstrateConfigManagement();
        
        // 4. 演示性能优化
        demonstratePerformanceOptimization();
        
        System.out.println("\n=== 演示完成 ===");
    }
    
    /**
     * 演示插件系统
     */
    private static void demonstratePluginSystem() {
        System.out.println("1. 插件系统演示");
        System.out.println("================");
        
        PluginManager pluginManager = PluginManager.getInstance();
        
        // 注册大气环境监测因子插件
        AtmosphericFactorPlugin plugin = new AtmosphericFactorPlugin();
        pluginManager.registerPlugin(plugin);
        
        System.out.println("✓ 注册插件: " + plugin.getName() + " v" + plugin.getVersion());
        System.out.println("✓ 支持的监测因子数量: " + plugin.getSupportedFactorCodes().size());
        System.out.println("✓ 支持的系统类型: " + plugin.getSupportedSystemTypes());
        
        // 验证监测因子
        MonitoringFactorPlugin.ValidationResult result = 
            pluginManager.validateFactor("SO2-Rtd", 15.6, "N");
        System.out.println("✓ SO2-Rtd 验证结果: " + (result.isValid() ? "通过" : "失败"));
        
        // 获取监测因子元数据
        MonitoringFactorPlugin.FactorMetadata metadata = plugin.getFactorMetadata("SO2-Rtd");
        if (metadata != null) {
            System.out.println("✓ SO2-Rtd 元数据:");
            System.out.println("  - 名称: " + metadata.getName());
            System.out.println("  - 单位: " + metadata.getUnit());
            System.out.println("  - 数值范围: " + metadata.getMinValue() + " - " + metadata.getMaxValue());
        }
        
        System.out.println();
    }
    
    /**
     * 演示增强编解码器
     */
    private static void demonstrateEnhancedCodec() {
        System.out.println("2. 增强编解码器演示");
        System.out.println("==================");
        
        try {
            // 创建增强编解码器
            Hj212EntityCodec codec = Hj212EntityCodecFactory.createEnhancedCodec();
            System.out.println("✓ 创建增强编解码器成功");
            
            // 解码协议数据
            Hj212Message message = codec.decode(SAMPLE_DATA);
            System.out.println("✓ 解码成功:");
            System.out.println("  - 设备标识: " + message.getMn());
            System.out.println("  - 系统编号: " + message.getSt());
            System.out.println("  - 命令编号: " + message.getCn());
            System.out.println("  - 请求编号: " + message.getQn());
            
            // 编码消息
            String encoded = codec.encode(message);
            System.out.println("✓ 编码成功，长度: " + encoded.length() + " 字符");
            
            // 验证编解码一致性
            boolean consistent = SAMPLE_DATA.equals(encoded);
            System.out.println("✓ 编解码一致性: " + (consistent ? "通过" : "失败"));
            
        } catch (Exception e) {
            System.err.println("✗ 增强编解码器演示失败: " + e.getMessage());
        }
        
        System.out.println();
    }
    
    /**
     * 演示配置管理
     */
    private static void demonstrateConfigManagement() {
        System.out.println("3. 配置管理演示");
        System.out.println("==============");
        
        // 创建自定义配置
        Hj212Config config = new Hj212Config();
        config.setEnableCache(true);
        config.setEnableValidation(true);
        config.setEnablePlugins(true);
        config.setCacheSize(2000);
        config.setDefaultVersion(ProtocolVersion.HJ212_2017);
        
        // 添加自定义属性
        config.setCustomProperty("timeout", 5000);
        config.setCustomProperty("retryCount", 3);
        
        System.out.println("✓ 创建自定义配置:");
        System.out.println("  - 缓存启用: " + config.isEnableCache());
        System.out.println("  - 验证启用: " + config.isEnableValidation());
        System.out.println("  - 插件启用: " + config.isEnablePlugins());
        System.out.println("  - 缓存大小: " + config.getCacheSize());
        System.out.println("  - 默认版本: " + config.getDefaultVersion().getFullName());
        System.out.println("  - 自定义属性: timeout=" + config.getCustomProperty("timeout"));
        
        // 使用配置创建编解码器
        try {
            Hj212EntityCodec codec = Hj212EntityCodecFactory.createEnhancedCodec(
                config.isEnableCache(),
                config.isEnableValidation(),
                config.getDefaultVersion()
            );
            System.out.println("✓ 使用自定义配置创建编解码器成功");
        } catch (Exception e) {
            System.err.println("✗ 配置管理演示失败: " + e.getMessage());
        }
        
        System.out.println();
    }
    
    /**
     * 演示性能优化
     */
    private static void demonstratePerformanceOptimization() {
        System.out.println("4. 性能优化演示");
        System.out.println("==============");
        
        // 创建高性能编解码器
        Hj212EntityCodec highPerformanceCodec = Hj212EntityCodecFactory.createHighPerformanceCodec();
        System.out.println("✓ 创建高性能编解码器");
        
        // 性能测试
        int testCount = 1000;
        long startTime = System.currentTimeMillis();
        
        try {
            for (int i = 0; i < testCount; i++) {
                Hj212Message message = highPerformanceCodec.decode(SAMPLE_DATA);
                String encoded = highPerformanceCodec.encode(message);
            }
            
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            
            System.out.println("✓ 性能测试结果:");
            System.out.println("  - 测试次数: " + testCount);
            System.out.println("  - 总耗时: " + duration + "ms");
            System.out.println("  - 平均耗时: " + String.format("%.2f", (double) duration / testCount) + "ms/次");
            System.out.println("  - 处理速度: " + String.format("%.0f", (double) testCount * 1000 / duration) + " 次/秒");
            
        } catch (Exception e) {
            System.err.println("✗ 性能测试失败: " + e.getMessage());
        }
        
        System.out.println();
    }
}
